var _columns = [
    { checkbox: true },
    { field: 'id', title: '标示符' },
    {
        title: '序号', field: 'showId',
        formatter: function (value, row, index) {
            return index + 1;
        }
    },
    { field: 'productName', title: '产品名称' },
    { field: 'processRoute', title: '工艺路线' },
    { field: 'unit', title: '单位' },
    {
        field: 'unitProduct', title: '单位产品取水量',
        formatter: function (value, row, index) {
            if (operation == 'view' || operation == 'export') {
                if (value == null || value == '') {
                    return '';
                } else {
                    return value;
                }
            } else {
                if (value == null || value == '') {
                    var e = '<a onclick="edit(\'' + index + '\', \'' + row.productName + '\', \'' + row.processRoute + '\', \'' + row.valueUp + '\', \'' + row.advancedValueUp + '\', \'' + row.id + '\')"><i class="fa fa-edit" ></i>编辑</a>';
                    return e;
                } else {
                    var e = '<a onclick="edit(\'' + index + '\', \'' + row.productName + '\', \'' + row.processRoute + '\',  \'' + row.valueUp + '\',  \'' + row.advancedValueUp + '\', \'' + row.id + '\')">' + value + '</a>';
                    return e;
                }
            }
        }
    },
    { field: 'valueUp', title: companyType + '取水定额指标',
        formatter: function (value, row, index) {
            //空数据
            if(value == -1) {
                return '';
            }
            return value;
        }
    },
    { field: 'advancedValueUp', title: '先进企业取水定额指标',
        formatter: function (value, row, index) {
            //空数据
            if(value == -1) {
                return '';
            }
            return value;
        }
    },
    { field: 'result', title: '核算结果' },
]

window.MathJax = {
    tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
    },
    chtml: {
        scale: 0.8
    }
};

var metaList = [];
var inputList = [];


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/entity_water_count/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            sortable: true,                     //是否启用排序
            sortOrder: "desc",
            columns: _columns,
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            last_id: entity_classified_standard_id,
        };
        return temp;
    };
    return oTableInit;
};

//返回按钮
$('#btn_return').on('click', function () {
    $('#page-wrapper').load('pages/entity_classified_standard.html');
});

//提交表格
$('#submit').on('click', function () {
    //输入框不能为空
    var data = $('#data_table').bootstrapTable('getData', false);//获取全部数据
    for (var i = 0; i < data.length; i++) {
        if (data[i]['unitProduct'] == null || data[i]['unitProduct'] == '') {
            alert("单位产品取水量不能为空！");
            return;
        }
    }

    //获取input
    var flag = 1;   //成功提交，更新entity_classified_standard的状态
    var input1, input2;
    for (var i = 0; i < data.length; i++) {
        for (var e in inputList) {
            if (data[i].productName == inputList[e].productName && data[i].processRoute == inputList[e].processRoute) {
                input1 = inputList[e].input1;
                input2 = inputList[e].input2;
                break;
            }
        }
        $.ajax({
            type: "post",
            url: "/entity_water_count/update",
            async: false,
            data: {
                'id': data[i].id,
                'unitProduct': data[i]['unitProduct'],
                'result': data[i]['result'],
                'input1': input1,
                'input2': input2,
            },
            error: function () {
                flag = 0;
                bootoast({
                    message: '通讯异常',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });
    }
    //都成功插入,修改对应的label_water_saving的状态
    if (flag == 1) {
        $.ajax({
            type: "post",
            url: "/entity_water_count/state_update",
            async: false,
            data: {
                'id': entity_classified_standard_id,
                'state': "已完成",
                'modifyTime': new Date()
            },
            success: function (data) {
                if (data['status'] == "success") {
                    $('#page-wrapper').load('pages/entity_classified_standard.html');
                }
            },
            error: function () {
                bootoast({
                    message: '通讯异常',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });
    } else {
        alert("插入失败");
        return;
    }
});

//保存表格
$('#save').on('click', function () {
    //输入框不能为空
    var data = $('#data_table').bootstrapTable('getData', false);//获取全部数据
    var flag = 0;   //成功提交，更新entity_classified_standard的状态
    var input1, input2;
    for (var i = 0; i < data.length; i++) {
        for (var e in inputList) {
            if (data[i].productName == inputList[e].productName && data[i].processRoute == inputList[e].processRoute) {
                input1 = inputList[e].input1;
                input2 = inputList[e].input2;
                break;
            }
        }
        $.ajax({
            type: "post",
            url: "/entity_water_count/update",
            async: false,
            data: {
                'id': data[i].id,
                'unitProduct': data[i]['unitProduct'],
                'result': data[i]['result'],
                'input1': input1,
                'input2': input2,
            },
            success: function (data) {
                if (data['status'] == "success") {
                    flag++;
                } else {
                    bootoast({
                        message: '插入失败\n' + data['msg'],
                        position: 'top',
                        type: 'danger',
                        timeout: 2,
                    });
                }
            },
            error: function () {
                bootoast({
                    message: '通讯异常',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });
    }
    //都成功插入,修改对应的label_water_saving的状态
    if (flag == data.length) {
        bootoast({
            message: '保存成功',
            position: 'top',
            type: 'success',
            timeout: 2,
        });
        $.ajax({
            type: "post",
            url: "/entity_water_count/state_update",
            async: false,
            data: {
                'id': entity_classified_standard_id,
                'state': "填写中",
                'modifyTime': new Date()
            },
            error: function () {
                bootoast({
                    message: '通讯异常',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });
    } else {
        alert("保存失败");
        return;
    }
});

//取消提交表格
$('#cancel').on('click', function () {
    //点击取消按钮，返回到label页，将状态改为填写中
    $.ajax({
        type: "post",
        url: "/entity_water_count/state_update",
        async: false,
        data: {
            'id': entity_classified_standard_id,
            'state': "填写中",
            'modifyTime': new Date()
        },
        success: function (data) {
            if (data['status'] == "success") {
                $('#page-wrapper').load('pages/entity_classified_standard.html');
            }
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
});

$(function () {

    var oTable = new TableInit();
    oTable.Init();

    //获取输入框数据
    $.ajax({
        url: "/entity_water_count/select",
        data: { last_id: entity_classified_standard_id },
        type: "get",
        async: false,
        success: function (result) {
            inputList = result['rows'];
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });

    if (operation == 'view') {
        $('#btn_select').hide();
        $('#btn_delete').hide();
        $('#save').hide();
        $('#submit').hide();
        $('#cancel').hide();
    } else if (operation == 'export') {
        $('#btn_select').hide();
        $('#btn_delete').hide();
        $('#save').hide();
        $('#submit').hide();
        $('#cancel').hide();

        bootbox.confirm({
            message: "确认导出？",
            locale: 'zh_CN',
            title: '操作提示',
            callback: function (result) {
                if (result) {
                    $("#data_table").tableExport({ fileName: '取水定额', type: "xls", escape: "false" });
                    $('#page-wrapper').load("pages/entity_classified_standard.html");
                } else {
                    $('#page-wrapper').load("pages/entity_classified_standard.html");
                }
            }
        });
    } else if (operation == 'edit') {

        //引入Mathjax
        var script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js';
        script.async = true;
        document.head.appendChild(script);
    }
    $('#data_table').bootstrapTable('hideColumn', 'id');

});

//获取元数据中的数据
function getMetaData() {
    $.ajax({
        url: "/entity_water_count/get_meta_data",
        data: 'entity_classified_standard_num=' + entity_classified_standard_num,
        type: "get",
        async: false,
        success: function (result) {
            metaList = result['rows'];
            getInsertData();
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
}

function getInsertData() {
    //查询ENTITY_STANDARD_INFO中的已有数据，插入时避免重复
    var tableList = [];
    // var productNameCount = 0;

    //获取表格中已有的数据
    $.ajax({
        url: "/entity_water_count/select",
        data: 'last_id=' + entity_classified_standard_id,
        type: "get",
        async: false,
        success: function (result) {
            var temp = result['rows'];
            for (var i = 0; i < temp.length; i++) {
                tableList.push({"productName": temp[i].productName, "processRoute": temp[i].processRoute});
            }
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });

    //插入数据
    var productName, processRoute;
    for (var i = 0; i < metaList.length; i++) {
        productName = metaList[i].productName;
        processRoute = metaList[i].processRoute;
        //判断是否要插入多选框
        var insertFlag = true;
        for (var j = 0; j < tableList.length; j++) {
            if (productName == tableList[j].productName && processRoute == tableList[j].processRoute) {
                insertFlag = false;
                break;
            }
        }
        if (insertFlag) {
            //插入多选框
            var div = document.getElementById('data_body');

            //添加选择框
            var selectDiv = document.createElement('div');
            selectDiv.setAttribute("class", "checkbox");
            div.append(selectDiv);

            //添加label
            var label = document.createElement("label");
            selectDiv.append(label);

            //添加input
            var input = document.createElement('input');
            input.setAttribute("type", "checkbox");
            input.setAttribute("name", "checkbox");
            input.value = productName + '\t' + processRoute;
            label.append(input);
            label.append(input.value);

            tableList.push({"productName": metaList[i].productName, "processRoute": metaList[i].processRoute});
        }
    }
}

var index;
var valueUp;
var id;

$('#btn_select').on('click', function () {
    // 清空多选框
    document.getElementById('data_body').innerHTML = '';

    //根据标准号，构建entity_water_count初始数据，插入到多选框
    getMetaData();

    $('#select_data').modal();
});

// 删除按钮
$("#btn_delete").click(function () {
    var arrselections = $("#data_table").bootstrapTable('getSelections');
    if (arrselections.length <= 0) {
        bootoast({
            message: '请选择有效数据',
            position: 'top',
            type: 'warning',
            timeout: 1.5,
        });
        return;
    }
    ids = [];
    for (var i = 0; i < arrselections.length; i++)
        ids.push(arrselections[i].id);
    bootbox.confirm({
        message: "确认要删除选择的数据吗？",
        locale: 'zh_CN',
        title: '操作提示',
        callback: function (result) {
            if (result) {
                $.ajax({
                    type: "post",
                    url: "/entity_water_count/delete",
                    async: false,
                    data: JSON.stringify(ids),
                    contentType: "application/json",
                    success: function (data) {
                        if (data['status'] == "success") {
                            bootoast({
                                message: '删除成功',
                                position: 'top',
                                type: 'success',
                                timeout: 1.5,
                            });
                            $("#data_table").bootstrapTable('refresh');
                        } else {
                            bootoast({
                                message: '删除失败\n' + data['msg'],
                                position: 'top',
                                type: 'danger',
                                timeout: 1.5,
                            });
                        }
                    }
                });
            }
        }
    })
});

$('#data_submit').on('click', function () {
    var selectedData = [];
    $("input[name='checkbox']:checked").each(function (i) {
        selectedData.push($(this).val())
    })

    var productName;
    var processRoute;
    var unit;
    var valueUp;
    var advancedValueUp;
    for (var i = 0; i < selectedData.length; i++) {
        selectedProductName = selectedData[i].split('\t')[0];
        selectedProcessRoute = selectedData[i].split('\t')[1];
        valueUp = -1;
        advancedValueUp = -1;
        for (var j = 0; j < metaList.length; j++) {
            if (selectedProductName == metaList[j].productName && selectedProcessRoute == metaList[j].processRoute) {
                productName = metaList[j].productName;
                processRoute = metaList[j].processRoute;
                unit = metaList[j].unit;
                if(metaList[j].industryStatus == companyType) {
                    valueUp = metaList[j].valueUp;
                } else if (metaList[j].industryStatus == '先进企业'){
                    advancedValueUp = metaList[j].valueUp;
                }

                //将新数据插入inputList
                inputList.push({ productName: productName, processRoute: processRoute, input1: -1, input2: -1 });
            }
        }

        $.ajax({
            type: "post",
            url: "/entity_water_count/insert_water_count_data",
            async: false,
            data: {
                'productName': productName,
                'processRoute': processRoute,
                'unit': unit,
                'valueUp': valueUp,
                'advancedValueUp': advancedValueUp,
                'entityClassifiedStandardId': entity_classified_standard_id,
                'standardNum': entity_classified_standard_num,
            },
            success: function () {
                $('#data_table').bootstrapTable('refresh');
            },
            error: function () {
                bootoast({
                    message: '通讯异常',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });
    }
    $('#select_data').modal('hide');
});

var formulaList = [
    {
        'standardNumber': 'GB/T 18916.24-2016',
        'formula': "$V_{ui} = \\frac {V_i}{Q}$",
        "label1": "$V_{ui}$ ——单位产品取水量，企业生产每吨麻纺织产品或百米麻纺织物所取用的水量，单位为立方米每吨（m³/t）或立方米每百米（m³/100 m）",
        "label2": "$V_i$ ——取水量，在一定计量时间内，企业生产某种麻纺织产品取用的水量，单位为立方米（m³）",
        "label3": "$Q$ ——产品产量，在一定计量时间内，企业生产的标准品的产量，单位为吨（t）或百米（100 m）",
    },
    {
        'standardNumber': 'GB/T 18916.25-2016',
        'formula': "$V_{ui} = \\frac {V_i}{Q}$",
        "label1": "$V_{ui}$ ——单位产品取水量，企业生产每吨粘胶纤维产品所取用的水量，单位为立方米每吨（m³/t）",
        "label2": "$V_i$ ——取水量，在一定计量时间内，企业生产某种粘胶纤维产品取用的水量，单位为立方米（m³）",
        "label3": "$Q$ ——产品产量，在一定计量时间内，企业生产的粘胶纤维产品产量，单位为吨（t）",
    },
    {
        'standardNumber': 'GB/T 18916.20-2016',
        'formula': "$V_{ui} = \\frac {V_i}{Q}$",
        "label1": "$V_{ui}$ ——单位化纤长丝织造产品取水量，企业每生产百米化纤长丝织造产品的取水量，单位为立方米每百米（m³/100 m）",
        "label2": "$V_i$ ——在一定计量时间内，企业生产某种化纤长丝织造产品的取水量，单位为立方米（m³）",
        "label3": "$Q$ 在一定计量时间内，生产标准化纤长丝织造产品的产量，单位为百米（100 m）",
    },
    {
        'standardNumber': 'GB/T 18916.21-2016',
        'formula': "$V_{ui} = \\frac {V_i}{Q}$",
        "label1": "$V_{ui}$ ——单位产品取水量，企业生产每吨产品或百米织物所取用的水量，单位为立方米每吨（m³/t）或立方米每百米(m³/100 m)",
        "label2": "$V_i$ ——在一定计量时间内，企业生产某种真丝绸产品去取用的水量，单位为立方米（m³）",
        "label3": "$Q$ 在一定计量时间内，企业生产的标准品的产量，单位为吨（t）或百米（100 m）",
    },
    {
        'standardNumber': 'GB/T 18916.14-2014',
        'formula': "$V_{ui} = \\frac {V_i}{Q}$",
        "label1": "$V_{ui}$ ——单位毛纺织产品取水量，企业生产每百米毛织物或每吨产品所取用的水量，单位为立方米每百米（m³/100 m）或立方米每吨(m³/t)",
        "label2": "$V_i$ ——在一定计量时间内，毛纺织企业生产某种合格品所取用的水量，单位为立方米（m³）",
        "label3": "$Q$ 在一定计量时间内，毛纺织企业生产的合格品的产量，单位为百米（100 m）或吨（t）",
    },
    {
        'standardNumber': 'GB/T 18916.4-2012',
        'formula': "$V_{ui} = \\frac {V_i}{Q}$",
        "label1": "$V_{ui}$ ——单位纺织染整产品取水量，企业生产每百米机织印染产品或每吨针织印染产品的取水量，单位为立方米每百米（m³/100 m）或立方米每吨(m³/t)",
        "label2": "$V_i$ ——在一定计量时间内，企业生产某种纺织染整产品的取水量，单位为立方米（m³）",
        "label3": "$Q$ 在一定计量时间内，生产标准纺织染整产品的产量，机织印染产品，单位为百米（100 m）；针织印染产品，单位为吨（t）",
    },
]

var index;
var valueUp;
var id;
var productName;
var processRoute;
var advancedValueUp;

function edit(showId, thisProductName, thisProcessRoute, rowValueUp, rowAdvancedValueUp, rowId) {
    $('#input1').val('');
    $('#input2').val('');

    index = showId;
    valueUp = rowValueUp;
    advancedValueUp = rowAdvancedValueUp;
    id = rowId;
    productName = thisProductName;
    processRoute = thisProcessRoute;

    var label1 = document.getElementById('label1');
    var label2 = document.getElementById('label2');
    var label3 = document.getElementById('label3');

    var flag = 0;
    for (var e in formulaList) {
        if (formulaList[e].standardNumber == entity_classified_standard_num) {
            label1.innerHTML = formulaList[e].label1;
            label2.innerHTML = formulaList[e].label2;
            label3.innerHTML = formulaList[e].label3;
            flag = 1;
            break;
        }
    }

    if (flag == 1) {
        for (var e in inputList) {
            if (inputList[e].productName == productName && inputList[e].processRoute == processRoute) {
                if (inputList[e].input1 != -1) {
                    $('#input1').val(inputList[e].input1);
                }
                if (inputList[e].input2 != -1) {
                    $('#input2').val(inputList[e].input2);
                }
                break;
            }
        }
        $('#formula').modal();
    } else {
        alert("此标准无对应公式！");
        return;
    }

    MathJax.typeset();
}

$('#formula_submit').on('click', function () {
    if ($('#input1').val() == '' || $('#input2').val() == '') {
        alert('请输入数值');
        return;
    }
    var input1 = parseFloat($('#input1').val());
    var input2 = parseFloat($('#input2').val());
    var value = (input1 / input2).toFixed(2);

    $('#technical_table').bootstrapTable('updateCell', {
        index: index,
        field: 'value',
        value: value
    });

    //更新inputList
    for (var e in inputList) {
        if (inputList[e].productName == productName && inputList[e].processRoute == processRoute) {
            inputList[e].input1 = $('#input1').val();
            inputList[e].input2 = $('#input2').val();
            break;
        }
    }

    $('#formula').modal('hide');
    judge(value, valueUp, advancedValueUp, id);
});

function judge(value, valueUp, advancedValueUp, id) {
    value = parseFloat(value);
    valueUp = parseFloat(valueUp);
    advancedValueUp = parseFloat(advancedValueUp);
    var result;
    if (value <= advancedValueUp) {
        result = "达到先进企业取水定额指标要求";
    } else if (value <= valueUp){
        result = "达到" + companyType + "取水定额指标要求";
    } else {
        result = "未达到" + companyType + "取水定额指标要求";
    }
    //更新单元格
    $('#data_table').bootstrapTable('updateByUniqueId', {
        id: id,
        row: {
            unitProduct: value,
            result: result
        }
    });
}